package org.sgy.mall.utils;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class MyPOITest {
	public static void main(String[] args) throws Exception {
		readExcel();
	}

	public static void readExcel() throws Exception {
		// 读取工作簿
		File file = new File("c:\\test1.xls");
		FileInputStream input = new FileInputStream(file);
		HSSFWorkbook workbook = new HSSFWorkbook(input);
		// 读取sheet
		HSSFSheet sheet = workbook.getSheetAt(0);
		// 读数据
		Iterator<Row> rowIterator = sheet.rowIterator();
		int rowNum = 1;
		while (rowIterator.hasNext()) {
			Row row = rowIterator.next();
			Iterator<Cell> cellIterator = row.cellIterator();
			int columnNum = 1;
			while (cellIterator.hasNext()) {
				Cell cell = cellIterator.next();
				System.out.println("行:" + rowNum + ",列:" + columnNum + "值:" + cell.getStringCellValue());
				columnNum++;
			}
			rowNum++;
		}
		workbook.close();
	}

	public static void writeExcel() throws Exception {
		// 建立工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 创建sheet
		HSSFSheet sheet = workbook.createSheet("my first sheet");
		// 写数据
		for (int i = 0; i < 10; i++) {
			HSSFRow row = sheet.createRow(i);
			for (int j = 0; j < 20; j++) {
				HSSFCell cell = row.createCell(j);
				cell.setCellValue(i + ":" + j);
			}
		}
		// 保存数据
		File file = new File("C:\\test.xls");
		file.createNewFile();
		workbook.write(file);
		workbook.close();
	}
}
